package com.coolwen.springmvc.controller;

import com.coolwen.springmvc.model.User;
import com.coolwen.springmvc.service.GroupService;
import com.coolwen.springmvc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author CoolWen
 * @version 2020-05-28 8:48
 */
@Controller
@RequestMapping("/user")//www.coolwen.com/user/list 浏浏览器访问的路径
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    private GroupService groupService;

    @ResponseBody
    @RequestMapping(value = "jasonuser", produces = "application/json; charset=utf-8")
    public String listJason() {
        return userService.listAllUser().toString();
    }

    @GetMapping(value = "users")//user/list
    public String list(Model model) {
        model.addAttribute("users", userService.listAllUser());
        return "user/list";
    }

    @GetMapping("/add")
    public String add(Model model) {
        model.addAttribute(new User());//model.addAttribute("user", new User());
        return "user/add";
    }

    @PostMapping("/add")
    public String add(@Valid User user, Errors errors) {
        System.out.println(user);
        if (errors.hasErrors()) {
            return "user/add";
        }
        userService.add(user, user.getGid());
        return "redirect:/user/users";
    }

    @GetMapping("/{id}")//Rest /user/12
    public String load(Model model, @PathVariable int id) {
        System.out.println(userService.load(id));
        User user = userService.load(id);
        model.addAttribute("user", user);
        model.addAttribute("group", groupService.load(user.getGid()));
        return "user/show";
    }
}
